<?php
/**
 *      [迷你云] (C)2009-2012 南京恒为网络科技.
 *   软件仅供研究与学习使用，如需商用，请访问www.miniyun.cn获得授权
 * 
 */
?>
<?php

class MFiles extends MModel {
    
    
    public static function buildFileDetail($file_path, $file_name)
    {
        $file_detail = new MFiles();
        $file_detail->file_name               = $file_name;
        $file_detail->file_path               = $file_path;
        return $file_detail;
    }
    
    
    public static function queryFilesByPath($path, $is_deleted = false) {
        $db_manager = MDbManager::getInstance ();
                                if ($is_deleted) {
            $is_deleted = intval ( true );
        } else {
            $is_deleted = intval ( false );
        }
        
        $sql = "select * from " . DB_PREFIX . "_files where file_path=\"{$path}\" ";
        $sql .= "AND is_deleted={$is_deleted}";
        FXP::trace("function: '{__FUNCTION__}',sql:'{$sql}'");
        
        return $db_manager->selectDb ( $sql );
    }
    
    
    public static function CreateFileDetail($file_detail, $user_id) {
        $sql = "insert into " . DB_PREFIX . "_files(user_id,file_type,parent_file_id,";
        $sql .= "file_create_time,file_update_time,file_name,version_id,";
        $sql .= "file_size,file_path,event_uuid,created_at,updated_at) values ";
                                $file_detail->event_uuid = MUtils::random_string ( MConst::LEN_EVENT_UUID );
        if (isset ( $file_detail->version_id ) === false)
            $file_detail->version_id = 0;
        
        $sql .= "({$user_id},$file_detail->file_type,";
        $sql .= "{$file_detail->parent_file_id},";
        $sql .= "{$file_detail->file_create_time},";
        $sql .= "{$file_detail->file_update_time},";
        $sql .= "\"{$file_detail->file_name}\",";
        $sql .= "{$file_detail->version_id},";
        $sql .= "{$file_detail->file_size},";
        $sql .= "\"{$file_detail->file_path}\",";
        $sql .= "\"{$file_detail->event_uuid}\",";
        $sql .= "now(),now())";
        $db_manager = MDbManager::getInstance ();
        $result = $db_manager->insertDb ( $sql );
        if ($result === false) {
            return false;
        }
        return $file_detail;
    }
    
    
    public static function updateRemoveFileDetail($file_detail) {
        $db_manager = MDbManager::getInstance();
        $sql = "UPDATE " . DB_PREFIX . "_files SET updated_at=now(), is_deleted = 1 ";
        $sql .= "WHERE file_path = \"{$file_detail->file_path}\" ";
        FXP::trace ( "handleRemoveObject: " . $sql );
        return $db_manager->updateDb ( $sql );
    }
    
    
    public static function updateFileDetailById($id, $updates = array()) {
        $sql = "UPDATE " . DB_PREFIX . "_files SET ";
        foreach ( $updates as $k => $v ) {
            if (is_string ( $v )) {
                $sql .= "$k=\"$v\"";
            } else {
                $sql .= "$k=$v";
            }
            $sql .= ",";
        }
        $sql .= "updated_at=now() WHERE id=$id";
        FXP::trace ( "function: '{updateFileDetailById}',sql:'{$sql}'" );
        $db_manager = MDbManager::getInstance ();
        return $db_manager->updateDb ( $sql );
    }
    
    
    public static function queryChildrenByParentId($userId,$parent_file_id, $is_deleted = false) {
        $sql = "SELECT * FROM " . DB_PREFIX . "_files WHERE parent_file_id=$parent_file_id";
        $sql .= " AND user_id=$userId AND is_deleted=";
        $sql .= ( int ) $is_deleted;
        FXP::trace ( "function: '{__FUNCTION__}',sql:'{$sql}'" );
        $result = mysql_query ( $sql );
        
        $ret_array = array ();
        if ($result === false) {
            $message = 'Invalid query: ' . mysql_error () . "\n";
            $message .= 'Whole query: ' . $sql;
            FXP::log ( $message, MLogger::LEVEL_WARNING );
            return false;
        }
        
        while ( $row = mysql_fetch_assoc ( $result ) ) {
            array_push ( $ret_array, $row );
        }
        
                                mysql_free_result ( $result );
        
        return $ret_array;
    }
    
    
    public static function updateRemoveChildrenFile($path) {
        $db_manager = MDbManager::getInstance ();
        $path .= "/";
        $sql = "UPDATE ".DB_PREFIX."_files SET updated_at=now(),is_deleted = 1 ";
        $sql .= "WHERE file_path like \"{$path}%\" ";
        FXP::trace ( "handleRemoveObject: " . $sql );
        return $db_manager->updateDb ( $sql );
    }
    
    
    public static function updateMoveChildrenFileDetail($user_id, $file_detail) {
        $relative_path = $file_detail->file_path;
        $relative_path .= "/";
        $from_path = $file_detail->from_path;
        $from_path .= "/";
        $db_manager = MDbManager::getInstance ();
        $sql = "UPDATE ".DB_PREFIX."_files SET updated_at=now(), file_path = ";
        $sql .= "CONCAT(\"$relative_path\", SUBSTRING(file_path,CHAR_LENGTH(\"$from_path\") + 1))";
        $sql .= " WHERE file_path like \"$from_path%\" and user_id = {$user_id}";
        FXP::trace ( "handleRemoveObject: " . $sql );
        return $db_manager->updateDb ( $sql );
    }
    
    
    public static function updateMoveFileDetail($file_detail)
    {
        $db_manager = MDbManager::getInstance();
        $sql = "UPDATE ".DB_PREFIX."_files SET updated_at=now(),file_path = \"{$file_detail->file_path}\", ";
        $sql .= " parent_file_id = {$file_detail->parent_file_id}, ";
        $sql .= "file_name =\"{$file_detail->file_name}\", ";
        $sql .= "is_deleted =0,";
        $sql .= "event_uuid = \"{$file_detail->event_uuid}\" ";
        $sql .= "WHERE id = {$file_detail->id}";
        FXP::trace ( "handleRemoveObject: " . $sql );
        return $db_manager->updateDb ( $sql );
    }
    
    public static function queryFileById($id) {
        $sql = "SELECT * FROM " . DB_PREFIX . "_files WHERE id={$id}";
        FXP::trace ( "function: '{queryFileById}',sql:'{$sql}'" );
        $db_manager = MDbManager::getInstance ();
        return $db_manager->selectDb ( $sql );
    }
    
    
    public static function queryChildrenFilesByPath($path, $is_sort=false) {
        $db_manager = MDbManager::getInstance();
        $path .= "/";
        $sql = "select * from ".DB_PREFIX."_files where file_path like \"{$path}%\" ";
        if ($is_sort === true) {
            $sql .= " order by parent_file_id desc";
        }
        FXP::trace ( "function: '{__FUNCTION__}',sql:'{$sql}'" );
        return $db_manager->selectDb ( $sql );
    }
    
    
    public static function batchCreateFileDetails($user_id, $file_details)
    {
        $sql  = "insert into ".DB_PREFIX."_files(user_id,file_type,parent_file_id,";
        $sql .= "file_create_time,file_update_time,file_name,version_id,";
        $sql .= "file_size, file_path, event_uuid,created_at,updated_at) values ";
        foreach ( $file_details as $file_detail ) {
            $sql .= "({$user_id},$file_detail->file_type,";
            $sql .= "{$file_detail->parent_file_id},";
            $sql .= "{$file_detail->file_create_time},";
            $sql .= "{$file_detail->file_update_time},";
            $sql .= "\"{$file_detail->file_name}\",";
            $sql .= "{$file_detail->version_id},";
            $sql .= "{$file_detail->file_size},";
            $sql .= "\"{$file_detail->file_path}\",";
            $sql .= "\"{$file_detail->event_uuid}\",";
            $sql .= "now(),now()),";
        }
        
                                $sql = substr ( $sql, 0, - 1 );
        
        $db_manager = MDbManager::getInstance ();
        $result = $db_manager->insertDb ( $sql );
        return $result;
    }
    
    
    public static function queryChildrenFilesByParentFileID($parent_file_id, $include_deleted = false, $user_id=null) {
        $db_manager = MDbManager::getInstance ();
        $sql = "select * from ".DB_PREFIX."_files where ";
        $sql .= " parent_file_id = {$parent_file_id} ";
                                if ($include_deleted == false) {
            $is_deleted = intval(false);
            $sql .= " AND is_deleted={$is_deleted}";
        }
        if ($user_id)
        {
            $sql .= " AND user_id={$user_id}";
        }
        FXP::trace ( "function: '{__FUNCTION__}',sql:'{$sql}'" );
        
        return $db_manager->selectDb ( $sql );
    }
    
    public static function queryAllFilesByPath($path) {
        $db_manager = MDbManager::getInstance ();
        $sql = "select * from " . DB_PREFIX . "_files where file_path=\"{$path}\" ";
        FXP::trace ( "function: " . __FUNCTION__ . ",sql:'{$sql}'" );
        
        return $db_manager->selectDb ( $sql );
    }
    
    
    public static function exchange2Object($file_detail,$signal = false) {
        $retval = new MFiles ();
        $temp = $file_detail;
        if ($signal == false) {
            $temp = $file_detail[0];
        }
        foreach ( $temp as $k => $v ) {
            $retval->$k = $v;
        }
        return $retval;
    }

    
    
    public static function updateFileDetailByPath($path, $updates) {
        if (empty($updates))
        {
            return false;
        }
        $sql  = "UPDATE " .DB_PREFIX . "_files SET ";
        foreach ($updates as $k => $v) {
            if (is_string($v)) {
                $sql .= "$k=\"$v\"";
            } else {
                $sql .= "$k=$v";
            }
            $sql .= ",";
        }
        $sql .= "updated_at=now() WHERE file_path=\"{$path}\"";
        FXP::trace("function: '{__FUNCTION__}',sql:'{$sql}'");
        $db_manager = MDbManager::getInstance();
        return $db_manager->updateDb($sql);
    }
    
    
    public static function searchFilesByPath($path, $query, $userID, $include_deleted=false) {
        $query =  str_replace("%","\\%",$query);
        $db_manager = MDbManager::getInstance();
        $sql = "select * from ".DB_PREFIX."_files where ";
        $sql .= " file_name like \"%{$query}%\" ";
        if ($path !== "/{$userID}/")
        {
            $sql .= " and file_path like \"{$path}%\" ";
        }
                                if ($include_deleted == false) {
            $is_deleted = intval ( $include_deleted );
            $sql .= " AND is_deleted={$is_deleted}";
        }

        FXP::trace ( "function: '{__FUNCTION__}',sql:'{$sql}'" );
        return $db_manager->selectDb ( $sql );
    }
    
    
    public static function findAll($condition = 1) {
        $db_manager = MDbManager::getInstance();
        $sql = "select * from ".DB_PREFIX."_files where ";
        $sql .= $condition;
        FXP::trace ( "function: '{findAll}',sql:'{$sql}'" );
        return $db_manager->selectDb ( $sql );
    }
    
    
    public static function deleteById($id) {
        $db_manager = MDbManager::getInstance();
        $sql = "delete from ".DB_PREFIX."_files where ";
        $sql .= "id = $id";
        FXP::trace ( "function: '{deleteById}',sql:'{$sql}'" );
        if (empty($id)) return false;
        return $db_manager->selectDb ( $sql );
    }
    
    
    public static function updateParentId($fromId,$toId) {
        $sql = "UPDATE " .DB_PREFIX . "_files SET ";
        $sql .= "parent_file_id=$toId";
        $sql .= " WHERE parent_file_id = $fromId";
        FXP::trace ( "function: '{updateParentId}',sql:'{$sql}'" );
        $db_manager = MDbManager::getInstance();
        $db_manager->updateDb($sql);
    }
    
    public function getUsedSpace($ids){
        $sql = "SELECT user_id,sum(file_size) as usedSpace FROM `".DB_PREFIX."_files` where user_id in(".$ids.") GROUP BY user_id";
        FXP::trace ( "function: '{getUsedSpace}',sql:'{$sql}'" );
        $db_manager = MDbManager::getInstance();
        return $db_manager->selectDb($sql);
    }
}
?>